﻿// TempFolderDescriptor
// 
// Class representig save information that is persisted in temp folder
// 
// FLMScan - Featured by FabLab Munich

using System;
using System.Collections.Generic;
using log4net;

namespace FLMScan.Tools
{
    class TempFolderDescriptor
    {
        public const int UnknownSaveIndex = 0;

        private ILog logger;
        private IFileSystem fileSystem;
        private String folderDescriptorPath;
        private int savedFolderIndex = UnknownSaveIndex;

        private const String LastSavedIndexPrefix = "lastSavedIndex:";
        private const String FolderDescriptorName = "FolderDescriptor.txt";

        public TempFolderDescriptor(IFileSystem fileSystem, String tempFolder)
        {
            logger = LogManager.GetLogger(typeof(TempFileManager));
            this.fileSystem = fileSystem;
            folderDescriptorPath = System.IO.Path.Combine(tempFolder, FolderDescriptorName);            
        }

        public String FilePath
        {
            get { return folderDescriptorPath; }
        }

        public int SavedFolderIndex
        {
            get { return savedFolderIndex; }
        }

        public void Deserialize()
        {
            try
            {
                List<String> contents = fileSystem.Deserialize(folderDescriptorPath);
                if (contents.Count > 0)
                {
                    String folderIndex = contents[0].Substring(LastSavedIndexPrefix.Length);
                    savedFolderIndex = int.Parse(folderIndex);
                }
            }
            // catch handlers for int.Parse            
            catch (ArgumentNullException ex)
            {
                logger.Error("Failure while analyzing temp folder descriptor!", ex);
                System.Diagnostics.Debug.Assert(false, "Failure while analyzing temp folder descriptor!");
            }
            catch (FormatException ex)
            {
                logger.Error("Failure while analyzing temp folder descriptor!", ex);
                System.Diagnostics.Debug.Assert(false, "Failure while analyzing temp folder descriptor!");
            }
            catch (OverflowException ex)
            {
                logger.Error("Failure while analyzing temp folder descriptor!", ex);
                System.Diagnostics.Debug.Assert(false, "Failure while analyzing temp folder descriptor!");
            }   
        }

        public void Serialize(int lastSavedIndex)
        {
            List<String> contents = new List<String>();
            contents.Add(LastSavedIndexPrefix + lastSavedIndex);
            fileSystem.Serialize(contents, folderDescriptorPath);
        }
    }
}
